package com.lb.trac.util;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.lb.trac.service.SearchService;

public abstract class AbstractBrowser implements Browser {
	
	

	private String paramPageName;
	private SearchService searchService;

	public SearchService getSearchService() {
		return searchService;
	}
	public void setSearchService(SearchService searchService) {
		this.searchService = searchService;
	}
	public String getParamPageName() {
		return paramPageName;
	}
	public void setParamPageName(String paramPageName) {
		this.paramPageName = paramPageName;
	}
	
	public int getPagineTotali(Integer count) {
		int pagineTotali = count / getItemsPerPage();
		if (count % getItemsPerPage() != 0) {
			pagineTotali += 1;
		}
		return pagineTotali;
	}
	
	
	
	public List<Page> getPages(HttpServletRequest request, Integer count) {
		List<Page> pages = new ArrayList<Page>();
		int aCounter = 1;
		int pagineTotali = getPagineTotali(count);
		int recordCounter = 0;
		Page prevPage = null;
		while (count >= 0) {
			Page _page = new Page();
			_page.setPagineTotali(pagineTotali);
			if (aCounter > 1) {
				_page.setPreviousPage(prevPage);
			}
			_page.setPage(aCounter++);
			for (int i = 0; i < getItemsPerPage(); i++, count--, recordCounter++) {
				if (recordCounter == 0) {
					_page.setFirstPage(true);
				}
				if (i == 0) {
					_page.setFirstRecord(recordCounter);
				}
				// if (i == searchService.getMaxResult()- 1) {
				// int nextRecord = i + searchService.getMaxResult();
				// if (nextRecord > count)
				// _page.setNextRecord(nextRecord);
				//
				// }
			}
			if (count <= 0) {
				_page.setLastPage(true);
			}
			pages.add(_page);
			prevPage = _page;
			request.getSession().setAttribute("recordCount", count);
		}
		request.getSession().setAttribute("pagesInMemo", pages);
		return pages;
	}

	public List<Page> preparaImpaginazione(HttpServletRequest request,
			Integer count) {
		return getPages(request, count);
	}

}
